package com.pearadmin.common.websocket;

import cn.hutool.db.Entity;
import com.google.common.collect.Range;
import com.pearadmin.common.tools.common.TimeS;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/WebSocket/{username}")
@Component
public class MyWebSocketServer {
	private static int onlineCount = 0;
	private static Map<String, MyWebSocketServer> clients = new ConcurrentHashMap<String, MyWebSocketServer>();
	@Value("${server.port}")
	private int port;
	private UserDao dao=new UserDao(port);
	private static List<Entity> s1=null; //签到范围
	private static String people=null;
	private static int yd=-1,sd=-1;//
	private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private Session session;
	private String username;


	public MyWebSocketServer(){
		super();
	}
	@OnOpen
	public void onOpen(@PathParam("username") String username, Session session)
			throws IOException {
		this.username = username;
		this.session = session;
		MyWebSocketServer.onlineCount++;
		clients.put(username, this);
		System.out.println(username+"已连接"+clients);
	}
	@OnClose
	public void onClose() throws IOException {
		clients.remove(username);
		MyWebSocketServer.onlineCount--;
	}
	@OnMessage
	public void onMessage(String message) throws IOException, InterruptedException, SQLException {
		System.out.println(message);
		synchronized (MyWebSocketServer.class){
			//防止重复打卡
			if(message.indexOf("add#")!=-1){
				if(people==null){//初始化第一次
					String s=df.format(new Date());
					int t= TimeS.getNowS(df.format(new Date()));
					s=s.substring(0,10);
					s1=dao.getTimeRange();
					for(int i=0;i<s1.size();i++){
						Range rg = (Range) s1.get(i).get("range");
						if(rg.contains(t)){
							System.out.println("在考勤时间内:"+s);
							boolean fl=dao.queryByLastPeopleTime(s, s1.get(i).getStr("start"), s1.get(i).getStr("stop"));
							if(fl){
								//判断是否已经在数据库中创建本签到时间段内的记录
								Entity str=dao.getLastPeopleTime();
								if(str.getStr("text").indexOf(message.split("#")[1])==-1){
									yd=Integer.parseInt( str.getStr("people1"));
									sd=Integer.parseInt( str.getStr("people2") )+1;
									people=str.getStr("text")+message.split("#")[1]+"#";
									dao.updateLastPeopleTime(yd, sd, people, s, s1.get(i).getStr("start"), s1.get(i).getStr("stop"));
									sendMessageAll("web_"+message);
								}
							}else{
								yd=dao.getPeopleNum();
								sd=1;
								people=message.split("#")[1]+"#";
								dao.insertLastPeopleTime(s, s1.get(i).getStr("start"), s1.get(i).getStr("stop"), yd, sd, people);
								sendMessageAll("sxjm");
							}
						}
					}
				}else{
					String s=df.format(new Date());
					int t=TimeS.getNowS(df.format(new Date()));
					s=s.substring(0,10);
					for(int i=0;i<s1.size();i++){
						Range rg = (Range) s1.get(i).get("range");
						if(rg.contains(t)){
							System.out.println("在考勤时间内:"+s);
							boolean fl=dao.queryByLastPeopleTime(s, s1.get(i).getStr("start"), s1.get(i).getStr("stop"));
							if(fl){//判断是否已经在数据库中创建本签到时间段内的记录
								if(people.indexOf(message.split("#")[1])==-1){
									sd=sd+1;
									people=people+message.split("#")[1]+"#";
									dao.updateLastPeopleTime(yd, sd, people, s, s1.get(i).getStr("start"), s1.get(i).getStr("stop"));
									sendMessageAll("web_"+message);
								}
							}else{
								yd=dao.getPeopleNum();
								sd=1;
								people=message.split("#")[1]+"#";
								dao.insertLastPeopleTime(s, s1.get(i).getStr("start"), s1.get(i).getStr("stop"), yd, sd, people);
								sendMessageAll("sxjm");
							}
						}
					}
				}
			}else if(message.equals("cs")){
				System.out.println("签到时间表重设");
				s1=dao.getTimeRange();
			}else if(message.equals("qk")){
				System.out.println("设备关闭");
				people=null;
				yd=-1;
				sd=-1;//
			}
		}
	}
	private void sleep(int i) {
		// TODO Auto-generated method stub
		
	}
	@OnError
	public void onError(Session session, Throwable error) {
		//error.printStackTrace();
	}
	public void sendMessageAll(String message) throws IOException {
		System.out.println("send+all"+message);
		for (MyWebSocketServer item : clients.values()) {
			item.session.getAsyncRemote().sendText(message);
		}
	}
	public static synchronized int getOnlineCount() {
		return onlineCount;
	}
	public static synchronized Map<String, MyWebSocketServer> getClients() {
		return clients;
	}
}